package com.yuven.appframework.network.interceptor

import android.text.TextUtils
import com.yuven.appframework.util.HttpDate
import com.yuven.appframework.util.TimeManager
import okhttp3.Headers
import okhttp3.Interceptor
import okhttp3.Response

class TimeCalibrationInterceptor : Interceptor {
    private var minResponseTime = Long.MAX_VALUE

    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        val startTime = System.nanoTime()
        val response = chain.proceed(request)
        val responseTime = System.nanoTime() - startTime

        val headers = response.headers
        calibration(responseTime, headers)
        return response
    }

    private fun calibration(responseTime: Long, headers: Headers) {
        //如果这一次的请求响应时间小于上一次，则更新本地维护的时间
        if (responseTime >= minResponseTime) {
            return;
        }

        val standardTime = headers["Date"]
        if (!TextUtils.isEmpty(standardTime)) {
            val parse = HttpDate.parse(standardTime);
            if (parse != null) {
                // 客户端请求过程一般大于比收到响应时间耗时，所以没有简单的除2 加上去，而是直接用该时间
                TimeManager.initServerTime(parse.getTime());
                minResponseTime = responseTime;
            }
        }
    }
}